const Koa = require("koa");
const WebSocket = require("koa-websocket");
const app = WebSocket(new Koa());
let ctxs = [];
// 简单的消息收发
app.ws.use((ctx, next) => {
  // 接收接入多个用户（每一个ctx代表一个用户）
  ctxs.push(ctx);
  ctx.websocket.on("message", (message) => {
    console.log(message, "message");
    for (let i = 0; i < ctxs.length; i++) {
      if (ctx == ctxs[i]) continue;
      ctxs[i].websocket.send(message.toString());
    }
  });
  ctx.websocket.on("close", (message) => {
    // 关闭时清除相关数据，防止出错
    let index = ctxs.indexOf(ctx);
    ctxs.splice(index, 1);
  });
});
app.listen(3001, () => console.log("http://localhost:3001"))